import { useLayoutEffect, useMemo, useState } from 'react'
import { Popover, Input } from 'antd'
import Color from './color'
import { cloneDeep } from 'loadsh'
import PopoverContent from './components/PopoverContent'
import './index.css'

const ColorPicker = ({
  value,
  showAlpha = true,
  showInput = true,
  colorFormat = 'hex',
  onChange = () => {}
}) => {
  const _color = new Color({ enableAlpha: showAlpha, format: colorFormat })
  const [color, setColor] = useState(_color)

  const displayedColor = useMemo(() => {
    if (!value) {
      return 'transparent'
    } else {
      const { r, g, b } = color.toRgb()
      const alpha = color.get('alpha')
      if (typeof alpha === 'number') {
        return showAlpha ? `rgba(${r}, ${g}, ${b}, ${alpha / 100})` : `rgb(${r}, ${g}, ${b})`
      }
    }
  }, [value, color])

  useLayoutEffect(() => {
    color.fromString(value)
    setColor(cloneDeep(color))
  }, [value])

  const onValueChange = (newValue) => {
    onChange(newValue)
  }

  const onColorChange = (newColor) => {
    setColor(cloneDeep(newColor))
    onChange(newColor.value)
  }

  const suffix = (
    <Popover
      overlayClassName="color-picker__popover"
      content={
        <PopoverContent
          showAlpha={showAlpha}
          displayedColor={displayedColor}
          color={color}
          value={value}
          onChange={onValueChange}
          onColorChange={onColorChange}
        />
      }
      trigger="click"
    >
      <div className="color__picker" style={{ backgroundColor: displayedColor }} />
    </Popover>
  )

  return (
    <>
      {showInput ? (
        <Input
          value={value}
          onChange={(e) => onValueChange(e.target.value)}
          suffix={suffix}
          size="small"
        />
      ) : (
        <>{suffix}</>
      )}
    </>
  )
}

export default ColorPicker
